﻿using System;
using System.Collections.Generic;
using System.Text;
using FeedDotNet.Common;
using FeedDotNet;
using System.Globalization;
using ConsoleApplication;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Reflection;using System.IO;
namespace ConsoleApplication
{
    class Program
    {
        const string FullFeedFileName = "fullfeed.xml";        
        private static string cachedFileName;        
        internal static string FeedCacheFilePath        
        {           
            get         
            {            
                if (string.IsNullOrEmpty(cachedFileName))    
                {
                    cachedFileName =
                        Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), FullFeedFileName);
                }            
                return cachedFileName;      
            }      
        }      
        static Feed LoadCacheFile()    
        {        
            if (File.Exists(FeedCacheFilePath) || 
                File.GetLastWriteTime(FeedCacheFilePath).Subtract(DateTime.Now).Hours > 36)  
            {              
                string text = File.ReadAllText(FeedCacheFilePath);  
                return FeedReader.ReadString(text);        
            }         
            else       
            {             
                List<IFeedProvider> originalFeedProvider = new List<IFeedProvider>();  
                originalFeedProvider.Add(new OriginalFeed(
                    string.Format("http://dl.dropbox.com/u/2412817/feeds/{0}", FullFeedFileName))); 
                Feed originalFeed = RSSMerger.FetchFeed(originalFeedProvider);   
                return originalFeed;       
            }      
        }
     
        static void Main(string[] args)
        {
            string password = args[0];

            //IMDbDictionary imdbDictionary = new IMDbDictionary();

            //for debug/proxy purposes
            ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(
                    delegate
                    { return true; }
                );

            string configStr = Encoding.UTF8.GetString(ProcessFeeds.requestURL("http://dl.dropbox.com/u/2412817/config.xml"));

            XMLConfig config = XMLConfig.FromString(configStr, password);

            Feed originalFeed = LoadCacheFile();

            DropBoxInterop interop = new DropBoxInterop(config.DropBoxAccountInfo.username, config.DropBoxAccountInfo.password);

            Console.WriteLine("Getting RSS Feeds");

            List<IFeedProvider> feedProviders = new List<IFeedProvider>();
            config.FeedUrls.ForEach(new Action<MovieFeed>(delegate (MovieFeed m)
                {
                    feedProviders.Add(m);
                }));

            List<MovieFeedItem> mergedFeeds = RSSMerger.FetchNewFeed(feedProviders);

            foreach (MovieFeedItem movieFeedItem in mergedFeeds)
            {
                string googleSearch = (movieFeedItem.Title +
                    (string.IsNullOrEmpty(movieFeedItem.year) ? "" : " " + movieFeedItem.year)
                 ).Replace('.', ' ');
                try
                {

                    Console.WriteLine("querying google for " + googleSearch);

                    movieFeedItem.imdbID = ProcessFeeds.getImdbID(googleSearch);
                }
                catch (Exception e)
                {
                    Console.Write("failed during query for " + googleSearch);
                }

                System.Threading.Thread.Sleep(500);
            }

            mergedFeeds = MovieFeedItem.Distinct(mergedFeeds);

            foreach (MovieFeedItem movieFeedItem in mergedFeeds)
            {
                try
                {
                    if (!string.IsNullOrEmpty(movieFeedItem.imdbID))
                    {
                        foreach (FeedItem mfi in originalFeed.Items)
                            if (movieFeedItem.Guid == mfi.Guid)
                                continue;

                        movieFeedItem.imageURL = ("http://dl.dropbox.com/u/2412817/posters/" + movieFeedItem.imdbID + ".jpg");

                        //Check it item poster is already uploaded to dropbox.
                        if (!ProcessFeeds.requestURLExits(movieFeedItem.imageURL))
                        {
                            byte[] imageBytes = ProcessFeeds.getImageByteStream("http://api.movieposterdb.com/image/" + movieFeedItem.imdbID + "/300/poster.jpg");
                            interop.UploadFile(movieFeedItem.imdbID + ".jpg", imageBytes, "posters/");
                        }
                        else
                        {
                            Console.WriteLine("");
                        }
                        ProcessFeeds.setMovieDBInfo(movieFeedItem);
                        ProcessFeeds.prepItemForPost(movieFeedItem);
                    }

                    Console.WriteLine(movieFeedItem.feedTitle);
                    Console.WriteLine(movieFeedItem.Title + "+" + movieFeedItem.year);
                    Console.WriteLine(movieFeedItem.imdbID);
                    Console.WriteLine("Guid: " + movieFeedItem.Guid);
                    Console.WriteLine();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed image and prep!");
                    Console.WriteLine(movieFeedItem.Title + "+" + movieFeedItem.year);
                    Console.WriteLine(movieFeedItem.imdbID);
                    Console.WriteLine("Guid: " + movieFeedItem.Guid);
                }
            }

            originalFeed.Items = MovieFeedItem.Union(originalFeed.Items, mergedFeeds);

            String finalFeed = FeedDotNetExporter.ExportFeed(originalFeed);
            //lets cache it, and only upload it once every day    
            if (!originalFeed.Published.HasValue || originalFeed.Published.Value.Subtract(DateTime.Now).Hours > 24)  
            {          
                originalFeed.Published = DateTime.Now; 
                interop.UploadFile("fullfeed.xml", ASCIIEncoding.UTF8.GetBytes(finalFeed), "feeds/");    
            }         

            File.WriteAllText(FeedCacheFilePath, finalFeed);      

            //now we want to only upload the last 24 hours of movies   
            //!!!!!!!NOTE!!!!!!!!t           
            //reusing the original feed, this is a destructive act, but we have  
            //luckily already cahced off the original feed before this, so we don't        
            //have a problem.        
            for (int i = originalFeed.Items.Count-1; i >= 0; i--)   
            {               
                if (!originalFeed.Items[i].Published.HasValue ||  
                    originalFeed.Items[i].Published.Value.Subtract(DateTime.Now).Days >= 1)    
                {                 
                    originalFeed.Items.RemoveAt(i);    
                }          
            }           

            finalFeed = FeedDotNetExporter.ExportFeed(originalFeed);      
            interop.UploadFile("feed.xml", ASCIIEncoding.UTF8.GetBytes(finalFeed), "feeds/");

            Console.WriteLine("Upload Complete");
            //Console.ReadLine();

            
            //Console.WriteLine(mergedFeeds);
            //IMDbPopulator imdbPopulator = new IMDbPopulator(imdbDictionary);
            //mergedFeeds = imdbPopulator.FillFeedWithIMDbData(mergedFeeds);

            //Dictionary<string, YahooNZBData> jsonData = 
            //    YahooPipesReader.ReadJSONPipe("http://pipes.yahoo.com/pipes/pipe.run?_id=d142703ab5404e867163fcbdbae914e3&_render=json");

            //mergedFeeds = NZBIndexParser.CreateFeedWithNzbs(mergedFeeds);

            //RSSGenerator generator = new RSSGenerator();
            //List<YahooNZBData> newNzbs = generator.PrependWithData(jsonData);
            //MovieDBProxy.FetchNewTitles(newNzbs);
            //generator.SaveFeed();
        }
    }
}
